import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/common/Settings.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/models/school/newStudentDto.dart';
import 'package:ichinesereader/models/student/StudentItem.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:intl/intl.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:reactive_segmented_control/reactive_segmented_control.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/service/user.dart';
import 'package:ichinesereader/utils/StrUtil.dart';

// ignore: must_be_immutable
class StudentProfileSettingsForTeacher extends StatelessWidget {
  StudentProfileSettingsForTeacher({
    Key? key,
    required this.studentId,
  }) : super(key: key);

  String? studentId;
  UserServiceProvider _userServiceProvider = new UserServiceProvider();

  @override
  Widget build(BuildContext context) {
    Log.debug('build StudentProfileSettingsForTeacher');
    final SchoolAdminController _schoolAdminController = Get.find();
    var box = Hive.box('appconfig');
    int _currentLevel = 1;

    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;

    Log.debug(
        "build StudentProfileSettingsForTeacher studentId=${studentId.toString()} classId=${_schoolAdminController.currentSchoolAdminClass.classId}");
    bool isCreate = StrUtil.notHasValue(studentId);

    FormGroup form;
    StudentDetailsEditFormModel editFormModel = StudentDetailsEditFormModel();
    StudentDetailsNewFormModel newFormModel = StudentDetailsNewFormModel();
    form = isCreate ? newFormModel.form : editFormModel.form;
    if (isCreate) {
      form
          .control("username")
          .setAsyncValidators([_asyncValidatorUniqueUsername]);
    }
    var dateformat = new DateFormat('MM/dd/yyyy');

    List<DropdownMenuItem> _progressLevels = [];
    Constants.levelOverallOptions.forEach((element) {
      _progressLevels.add(
        DropdownMenuItem(
          value: element.value,
          child: Text(
            element.label.toString(),
          ),
        ),
      );
    });

    void _onUpdate() {
      Log.debug("form.valid=${form.valid} form.value=${form.value}");
      if (!form.valid) {
        form.markAllAsTouched();
        return;
      }
      StudentDetailsDto dto = new StudentDetailsDto();
      dto.userName = form.control('username').value;
      dto.email = form.control('email').value;
      if (form.control('dateofbirth').value != null)
        dto.dateOfBirth = dateformat.format(form.control('dateofbirth').value);
      dto.firstName = form.control('firstname').value;
      dto.lastName = form.control('lastname').value;
      dto.gender = form.control('gender').value;
      dto.nickName = form.control('nickname').value;
      dto.level = form.control('level').value ?? 'level1';
      dto.settings = new Settings();
      dto.settings?.pinyin = form.control('pinyinenabled').value;
      dto.settings?.lang = form.control('audiotype').value;
      dto.settings?.language = form.control('texttype').value;

      _schoolAdminController.updateStudent(dto).then((statusMessage) {
        if (statusMessage.status == 1000) {
          showSnackMsg('Successfully updated');
          // Get.snackbar('Message'.tr, 'Successfully updated'.tr,
          //     backgroundColor: Theme.of(context).primaryColor,
          //     colorText: Theme.of(context).primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);

          if (isTeacher)
            Get.offAndToNamed("/teacher/students");
          else
            Get.offAndToNamed("/schooladmin/students");
        } else {
          showSnackMsg('Error to update student');
          // Get.snackbar('Message'.tr, 'Error to update student'.tr,
          //     backgroundColor: Theme.of(context).primaryColor,
          //     colorText: Theme.of(context).primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
        }
      });
    }

    void _onCreate() {
      Log.debug("form.valid=${form.valid} form.value=${form.value}");
      if (!form.valid) {
        form.markAllAsTouched();
        return;
      }
      StudentDetailsDto dto = new StudentDetailsDto();
      dto.userName = form.control('username').value;
      dto.password = form.control('password').value;
      dto.email = form.control('email').value;
      dto.parentEmail = form.control('parentemail').value;
      if (form.control('dateofbirth').value != null)
        dto.dateOfBirth = dateformat.format(form.control('dateofbirth').value);
      dto.firstName = form.control('firstname').value;
      dto.lastName = form.control('lastname').value;
      dto.gender = form.control('gender').value;
      dto.nickName = form.control('nickname').value;
      dto.level = form.control('level').value != null
          ? form.control('level').value
          : 'level1';
      dto.settings = new Settings();
      dto.settings?.pinyin = form.control('pinyinenabled').value;
      dto.settings?.lang = form.control('audiotype').value;
      dto.settings?.language = form.control('texttype').value;

      // String _classId =
      //     _schoolAdminController.currentSchoolAdminClass.classId != null
      //         ? _schoolAdminController.currentSchoolAdminClass.classId
      //             .toString()
      //         : '';
      String _classId =
          box.get(CacheManagerKey['currentclass'].toString()) ?? 'All';

      _schoolAdminController.createStudent(_classId, dto).then((statusMessage) {
        if (statusMessage.status == 1000) {
          if (_classId == "All") {
            _schoolAdminController.fetchSchoolAllStudents(0, 200);
          } else {
            // if (_classId != '') {
            //   StudentToClassDto studentDto = new StudentToClassDto();
            //   studentDto.classId = _classId;
            //   studentDto.studentsUserName = [];
            //   studentDto.studentsUserName?.add(dto.userName.toString());
            //   _schoolAdminController.addCreatedStudentsToClass(studentDto);
            // }
            _schoolAdminController.fetchSchoolStudentsByClassId(_classId, true);

            Future.delayed(const Duration(milliseconds: 2000), () {
              if (isTeacher)
                Get.offAndToNamed("/teacher/students");
              else
                Get.offAndToNamed("/schooladmin/students");
            });
          }
          showSnackMsg(statusMessage.message.toString());
          // Get.snackbar('Message'.tr, statusMessage.message.toString(),
          //     //'Successfully created'.tr,
          //     backgroundColor: Theme.of(context).primaryColor,
          //     colorText: Theme.of(context).primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
        } else {
          showSnackMsg(statusMessage.message.toString());
          // Get.snackbar('Message'.tr, statusMessage.message.toString(),
          //     backgroundColor: Theme.of(context).primaryColor,
          //     colorText: Theme.of(context).primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
        }
      });
      // if (_schoolAdminController.statusMessageResult.value.status == 1000) {
      //   String _classId =
      //       _schoolAdminController.currentSchoolAdminClass.classId.toString();

      //   StudentToClassDto studentDto = new StudentToClassDto();
      //   studentDto.classId = _classId;
      //   studentDto.studentsUserName = [];
      //   studentDto.studentsUserName?.add(dto.userName.toString());

      //   _schoolAdminController.addCreatedStudentsToClass(studentDto);

      //   Get.snackbar('Message'.tr, 'Successfully created'.tr,
      //       backgroundColor: Theme.of(context).primaryColor,
      //       colorText: Theme.of(context).primaryColorLight,
      //       snackPosition: SnackPosition.BOTTOM);

      //   if (_classId == "All") {
      //     _schoolAdminController.fetchSchoolAllStudents(0, 20);
      //   } else {
      //     _schoolAdminController.fetchSchoolStudentsByClassId(_classId, true);
      //   }
      //   Future.delayed(const Duration(milliseconds: 1000), () {
      //     if (isTeacher)
      //       Get.offAndToNamed("/teacher/students");
      //     else
      //       Get.offAndToNamed("/schooladmin/students");
      //   });
      // } else {
      //   Get.snackbar('Message'.tr, 'Error to create student'.tr,
      //       backgroundColor: Theme.of(context).primaryColor,
      //       colorText: Theme.of(context).primaryColorLight,
      //       snackPosition: SnackPosition.BOTTOM);
      // }
    }

    List<Widget> _buildObxForm() {
      return <Widget>[
        ReactiveTextField(
          formControlName: 'username',
          validationMessages: {
            'unique': (_) => 'The user name is already used'.tr,
          },
          style: Theme.of(context).textTheme.titleSmall,
          decoration: InputDecoration(
            labelText: '*User Name'.tr,
          ),
          readOnly: !isCreate,
        ),
        SizedBox(
          height: 12,
        ),
        isCreate
            ? ReactiveTextField(
                formControlName: 'password',
                style: Theme.of(context).textTheme.titleSmall,
                decoration: InputDecoration(
                  labelText: '*Password'.tr,
                ),
              )
            : Visibility(
                child: Text(''),
                visible: false,
              ),
        isCreate
            ? SizedBox(
                height: 12,
              )
            : Visibility(
                child: Text(''),
                visible: false,
              ),
        ReactiveTextField(
          formControlName: 'firstname',
          style: Theme.of(context).textTheme.titleSmall,
          decoration: InputDecoration(
            labelText: '*First Name'.tr,
          ),
          maxLength: 150,
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveTextField(
          formControlName: 'lastname',
          style: Theme.of(context).textTheme.titleSmall,
          decoration: InputDecoration(
            labelText: '*Last Name'.tr,
          ),
          maxLength: 150,
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveTextField(
          formControlName: 'nickname',
          style: Theme.of(context).textTheme.titleSmall,
          decoration: InputDecoration(
            labelText: 'Nick Name'.tr,
          ),
          maxLength: 150,
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveTextField(
          formControlName: 'email',
          style: Theme.of(context).textTheme.titleSmall,
          decoration: InputDecoration(
            labelText: 'Email'.tr,
          ),
        ),
        SizedBox(
          height: 12,
        ),
        isCreate
            ? ReactiveTextField(
                formControlName: 'parentemail',
                style: Theme.of(context).textTheme.titleSmall,
                decoration: InputDecoration(
                  labelText: 'Parent Email'.tr,
                ),
              )
            : Visibility(
                child: Text(''),
                visible: false,
              ),
        isCreate
            ? SizedBox(
                height: 12,
              )
            : Visibility(
                child: Text(''),
                visible: false,
              ),
        ReactiveTextField<DateTime>(
          formControlName: 'dateofbirth',
          readOnly: true,
          decoration: InputDecoration(
            labelText: 'Date of Birth'.tr,
            suffixIcon: ReactiveDatePicker<DateTime>(
              formControlName: 'dateofbirth',
              firstDate: DateTime(1990),
              lastDate: DateTime(2030),
              builder: (context, picker, child) {
                return IconButton(
                  onPressed: picker.showPicker,
                  icon: const Icon(Icons.date_range),
                );
              },
            ),
          ),
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveSegmentedControl<String, String>(
          formControlName: 'gender',
          decoration: InputDecoration(
            labelText: 'Gender'.tr,
            border: OutlineInputBorder(),
            helperText: '',
          ),
          unselectedColor: Get.theme.primaryColorLight,
          padding: const EdgeInsets.all(0),
          children: {
            'male': Text('Male'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
            'female': Text('Female'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
          },
        ),
        SizedBox(height: 12.0),
        ReactiveDropdownField<dynamic>(
          formControlName: 'level',
          decoration: InputDecoration(
            labelText: 'Choose Level'.tr,
          ),
          items: _progressLevels,
          onChanged: (level) {
            var levelvalue = level.value;

            if (level.value == 'nm-assessment' ||
                level.value == 'nh-assessment' ||
                level.value == 'il-assessment' ||
                level.value == 'im-assessment' ||
                level.value == 'ih-assessment') {
              form.control('level').value = 'level${_currentLevel.toString()}';

              showSnackMsg('Assessment level could not be choosed manually!');

              // Get.snackbar('Message'.tr,
              //     'Assessment level could not be choosed manually!'.tr,
              //     backgroundColor: Theme.of(context).primaryColor,
              //     colorText: Theme.of(context).primaryColorLight,
              //     snackPosition: SnackPosition.BOTTOM);
              return;
            }

            int changedLevel =
                int.tryParse(levelvalue.replaceAll('level', '')) ?? 1;
            // if (level.value == 'nm-assessment') {
            //   changedLevel = 6;
            // }
            // if (level.value == 'nh-assessment') {
            //   changedLevel = 9;
            // }
            // if (level.value == 'il-assessment') {
            //   changedLevel = 12;
            // }
            // if (level.value == 'im-assessment') {
            //   changedLevel = 14;
            // }
            // if (level.value == 'ih-assessment') {
            //   changedLevel = 17;
            // }

            if (changedLevel < _currentLevel && !isCreate) {
              Get.defaultDialog(
                backgroundColor: Get.isDarkMode
                    ? (Color(0xff333333))
                    : Color.fromARGB(255, 234, 241, 238),
                title: 'WARNING'.tr,
                content: Container(
                  width: 360,
                  child: Text(
                    "Level downgrade will result in DATA RESET for students' previous reading progress, all books and quizzes between the changing levels will require to redo as the result, however, the points earned will not be affected. Please confirm the changes, thanks.",
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        letterSpacing: 1,
                        color:
                            Get.isDarkMode ? Color(0xffcccccc) : Colors.black,
                        fontSize: 20),
                  ),
                ),
                //cancelTextColor: Theme.of(context).colorScheme.secondary,
                //confirmTextColor: Theme.of(context).colorScheme.secondary,
                onCancel: () {
                  form.control('level').value =
                      'level${_currentLevel.toString()}';
                },
                onConfirm: () {
                  form.control('level').value = level.value;
                  Navigator.of(context).pop();
                },
              );
            }
          },
        ),
        SizedBox(
          height: 18,
        ),
        ReactiveSegmentedControl<String, String>(
          formControlName: 'audiotype',
          decoration: InputDecoration(
            labelText: 'Audio'.tr,
            border: OutlineInputBorder(),
            helperText: '',
          ),
          unselectedColor: Get.theme.primaryColorLight,
          padding: const EdgeInsets.all(0),
          children: {
            'Mandarin': Text('Mandarin'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
            'Cantonese': Text('Cantonese'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
            'No_audio': Text('No Audio'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
          },
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveSwitchListTile(
          title: Text(
            'Pinyin'.tr,
            style: Theme.of(context).textTheme.displaySmall,
          ),
          subtitle: Text(
            'When text option set to NO TEXT, pinyin can not be displayed.'.tr,
            style: Theme.of(context).textTheme.labelSmall,
          ),
          formControlName: 'pinyinenabled',
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveSegmentedControl<String, String>(
          formControlName: 'texttype',
          decoration: InputDecoration(
            labelText: 'Text'.tr,
            border: OutlineInputBorder(),
            helperText: '',
          ),
          padding: const EdgeInsets.all(0.0),
          unselectedColor: Get.theme.primaryColorLight,
          children: {
            'Simplified': Text('Simplified'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
            'Traditional': Text('Traditional'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
            'No text': Text('No Text'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
          },
        ),
        SizedBox(
          height: 12,
        ),
        SizedBox(
          height: 12,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            ReactiveFormConsumer(
              builder: (context, form, child) {
                return ElevatedButton(
                    child: Text(
                      'Submit'.tr,
                      style: TextStyle(
                        color: Color(0xffd8ffff),
                        letterSpacing: 1.0,
                      ),
                    ),
                    onPressed: isCreate ? _onCreate : _onUpdate);
              },
            ),
          ],
        ),
      ];
    }

    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: CustomAppBar(
          title: isCreate ? 'Create Student'.tr : 'Edit Student'.tr),
      body: Obx(() {
        var studentItemCount = _schoolAdminController.studentItems.length;
        Log.debug(studentItemCount.toString());

        StudentItem student;
        if (isCreate) {
          student = new StudentItem(settings: new Settings());
        } else {
          student = _schoolAdminController.studentItems
              .where((element) => element.id == studentId)
              .first;
        }
        Settings _classSettings = student.settings as Settings;
        form.control('username').value = student.userName;
        form.control('firstname').value = student.firstName;
        form.control('lastname').value = student.lastName;
        form.control('email').value = student.email;
        if (student.dateOfBirth != null)
          form.control('dateofbirth').value =
              dateformat.parse(student.dateOfBirth.toString());
        form.control('nickname').value = student.nickName;
        form.control('gender').value = student.gender ?? 'male';
        form.control('level').value = student.level;
        form.control('texttype').value =
            _classSettings.language ?? 'Simplified';
        form.control('audiotype').value = _classSettings.lang ?? 'Mandarin';
        form.control('pinyinenabled').value = _classSettings.pinyin ?? true;

        if (student.level != null && student.level != '') {
          _currentLevel =
              int.tryParse(student.level!.replaceAll('level', '')) ?? 1;
          if (student.level == 'nm-assessment') {
            _currentLevel = 6;
          }
          if (student.level == 'nh-assessment') {
            _currentLevel = 9;
          }
          if (student.level == 'il-assessment') {
            _currentLevel = 12;
          }
          if (student.level == 'im-assessment') {
            _currentLevel = 14;
          }
          if (student.level == 'ih-assessment') {
            _currentLevel = 17;
          }
        }

        return Container(
          padding: EdgeInsets.all(60),
          decoration: BoxDecoration(
            color:
                Get.isDarkMode ? Colors.black.withOpacity(0.1) : Colors.white,
          ),
          child: SingleChildScrollView(
            primary: false,
            child: Padding(
              padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
              child: ReactiveForm(
                formGroup: form,
                child: Column(
                  children: _buildObxForm(),
                ),
              ),
            ),
          ),
        );
      }),
    );
  }

  /// Async validator example that simulates a request to a server
  /// and validates if the email of the user is unique.
  Future<Map<String, dynamic>?> _asyncValidatorUniqueUsername(
      AbstractControl<dynamic> control) async {
    final error = {'unique': false};
    String userName = control.value;
    Log.debug('_asyncValidatorUniqueUsername userName=$userName');
    if (userName != '') {
      final isUsernameAvailable =
          await _userServiceProvider.usernameAvailable(userName);
      Log.debug(
          '_asyncValidatorUniqueUsername userName=$userName usernameAvailable=$isUsernameAvailable');
      if (!isUsernameAvailable) {
        control.markAsTouched();
        return error;
      }
    }
    return null;
  }
}
